package com.sunlands.qdcy.deskmate.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunlands.qdcy.deskmate.common.annotation.AutoLog;
import com.sunlands.qdcy.deskmate.dao.pojo.OrderRecordDO;
import com.sunlands.qdcy.deskmate.dao.pojo.PaymentAppleFailRecord;
import com.sunlands.qdcy.deskmate.dao.pojo.PaymentAppleRecord;
import com.sunlands.qdcy.deskmate.service.ApplePayService;
import com.sunlands.qdcy.deskmate.vo.AppleReceiptVO;
import com.sunlands.qdcy.deskmate.vo.BusinessResult;
import com.sunlands.qdcy.deskmate.vo.Order;
import com.sunlands.qdcy.deskmate.vo.feign.VipSetMealVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * @author zl
 * @version 1.0
 * @date Created in 2020/4/10
 */
@Slf4j
@RestController
@RequestMapping("/pay/apple")
@Api(tags = {"苹果支付相关接口"})
public class ApplePayConroller extends BaseController{

    @Autowired
    private ApplePayService applePayService;

    @AutoLog
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/create-order")
    @ApiOperation(value = "APP调用-苹果支付下单接口,只传 goodsNumber即可", response = OrderRecordDO.class)
    public BusinessResult<OrderRecordDO> createOrder(@RequestBody Order order) {
        //校验信息
        Asserts.notNull(order.getGoodsNumber(), "商品编号不能为空！");
        order.setUserId(currentUserId());
        //调用vip服务获取商品信息，校验商品编号
        VipSetMealVO setMeal = userCenterService.getVipSetMeal(order.getGoodsNumber()).getData();
        Asserts.notNull(setMeal, "没有查询到对应的商品信息！id = " + order.getGoodsNumber());

        order.setTotalAmount(setMeal.getPrice());
        order.setSubject(setMeal.getName());
        order.setBody(setMeal.getContent());

        OrderRecordDO orderRecordDO = applePayService.createOrder(order);

        log.info("app苹果支付下单成功 response = {}", orderRecordDO);
        return BusinessResult.createSuccessInstance(orderRecordDO);
    }

    @AutoLog
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/receipt")
    @ApiOperation(value = "APP调用-提交支付凭证（不立刻返回验证结果）")
    public BusinessResult<OrderRecordDO> receipt(@RequestBody AppleReceiptVO receiptVO) {
        log.info("用户{}提交支付凭证{}",currentUserId(), JSON.toJSONString(receiptVO));

        Asserts.notNull(receiptVO.getOutTradeNo(), "订单号不能为空！");
        Asserts.notNull(receiptVO.getReceiptData(), "支付凭证不能为空！");
//        Asserts.notNull(receiptVO.getTransactionId(), "苹果交易号不能为空！");
        Asserts.notNull(receiptVO.getProductId(), "苹果支付id不能为空！");

        receiptVO.setUserId(currentUserId());
        PaymentAppleRecord paymentAppleRecord = applePayService.saveAndVerifyReceipt(receiptVO);

        log.info("app支付苹果提交支付凭证 response = {}", paymentAppleRecord);
        return BusinessResult.createSuccessInstance(null);
    }

    @AutoLog
    @ApiOperation(value = "工具-苹果订单状态查询", response = BusinessResult.class)
    @GetMapping("/query")
    public BusinessResult<JSONObject> query(@RequestParam String outTradeNo) {
        PaymentAppleRecord paymentAppleRecord = applePayService.findByOutTradeNo(outTradeNo);
        JSONObject jsonObject = JSON.parseObject(applePayService.pullOrderStatus(paymentAppleRecord));
        return BusinessResult.createSuccessInstance(jsonObject);
    }

    @AutoLog
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/appleFailRecord")
    @ApiOperation(value = "苹果支付异常记录")
    public BusinessResult<Void> appleFailRecord(@RequestBody PaymentAppleFailRecord appleFailRecord) {
        appleFailRecord.setUserId(currentUserId());
        log.warn("苹果支付异常记录,userId={},outTradeNo={}",currentUserId(),appleFailRecord.getOutTradeNo());
        applePayService.saveAppleFailRecord(appleFailRecord);
        return BusinessResult.createSuccessInstance(null);
    }

    @AutoLog
    @GetMapping("/verifyFailRecord")
    @ApiOperation(value = "验证苹果支付异常记录")
    public BusinessResult<PaymentAppleFailRecord> verifyFailRecord(Long id) {
        PaymentAppleFailRecord appleFailRecord = applePayService.verifyFailRecord(id);
        return BusinessResult.createSuccessInstance(appleFailRecord);
    }



}
